package goleetcode

func checkValidGrid(grid [][]int) bool {
	if grid[0][0] != 0 {
		return false
	}

	n := len(grid)
	indices := make([][2]int, n * n)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			indices[grid[i][j]][0] = i
			indices[grid[i][j]][1] = j
		}
	}

	for i := 1; i < n * n; i++ {
		dx := abs(indices[i][0] - indices[i-1][0])
		dy := abs(indices[i][1] - indices[i-1][1])
		if dx * dy != 2 {
			return false
		}
	}

	return true
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}